package com.sangcomz.fishbun.permission;

import com.sangcomz.fishbun.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.global.resource.Element;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.security.SystemPermission;
import ohos.security.permission.PermissionState;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;


/**
 * Created by sangc on 2015-10-12.
 */
public class PermissionCheck {
    private Context context;

    public PermissionCheck(Context context) {
        this.context = context;
    }

    public boolean checkPermission(List<String> permissionList, int requestCode) {
        if (context instanceof AbilitySlice) {
            List<String> needRequestPermissionList = new ArrayList<>();
            for (String permission : permissionList) {
                if (context.verifySelfPermission(permission) != PermissionState.STATE_ALLOWED) {
                    needRequestPermissionList.add(permission);
                }
            }
            if (needRequestPermissionList.isEmpty()) {
                return true;
            } else {
                context.requestPermissionsFromUser(needRequestPermissionList.toArray(new String[0]), requestCode);
                return false;
            }
        }
        return false;
    }

    public boolean checkStoragePermission(int requestCode) {
        return checkPermission(
                Arrays.asList(SystemPermission.READ_USER_STORAGE, SystemPermission.WRITE_USER_STORAGE),
                requestCode
        );
    }

    public boolean checkCameraPermission(int requestCode) {
        List<String> permissions = context.getAbilityInfo().getPermissions();
        if (permissions.contains(SystemPermission.CAMERA)) {
            return checkPermission(Collections.singletonList(SystemPermission.CAMERA), requestCode);
        } else {
            return false;
        }
    }

    public void showPermissionDialog() {
        try {
            Element element = context.getResourceManager().getElement(ResourceTable.String_msg_permission);
            new ToastDialog(context).setText(element.getString()).show();
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.printStackTrace();
        }
    }

}